<template>
  <div class="page-container">
    <splitpanes class="default-theme">
      <pane size="15" min-size="0" max-size="25">
        <div class="department-container card">
          <el-input v-model.trim="departmentLabel" placeholder="请输入部门名称" clearable></el-input>
          <el-tree
            class="mt-20"
            ref="treeRef"
            default-expand-all
            :data="departmentList"
            :props="{
              children: 'children',
              label: 'label'
            }"
            :filter-node-method="filterDepartment"
            @node-click="tapDepartment"
          />
        </div>
      </pane>
      <pane class="page-container">
        <!-- 筛选栏 -->
        <TableFilter v-if="showFilter" @submit="submitFilter" @reset="resetFilter"></TableFilter>
        <!-- 表格主体 -->
        <div class="table-container card">
          <!-- 工具栏 -->
          <div class="table-control">
            <el-button type="primary" plain icon="Plus" @click="add">新增</el-button>
            <el-button type="danger" plain icon="Delete" @click="batchDelete">批量删除</el-button>
          </div>
          <el-table v-loading="loading" :data="tableData" border @selection-change="selectionChange">
            <el-table-column type="selection" align="center" width="50" fixed="left" />
            <el-table-column prop="id" label="UID" align="center" width="120" fixed="left"></el-table-column>
            <el-table-column prop="username" label="用户名" width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="nickname" label="用户昵称" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="avatar" label="头像" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="email" label="邮箱" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="phone" label="手机" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="roles" label="角色" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="tags" label="标签" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="department" label="部门" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="signature" label="签名" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="remark" label="备注" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="birthday" label="生日" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="gender" label="性别" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="status" label="状态" align="center" width="120">
              <template #default="scope">
                <DictTag :value="scope.row.status" :list="sys_status" :type="scope.row.status == 1 ? 'primary' : 'danger'"></DictTag>
              </template>
            </el-table-column>
            <el-table-column prop="registerTime" label="注册时间" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="registerIp" label="注册IP" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="loginTime" label="最近登录" min-width="240" show-overflow-tooltip></el-table-column>
            <el-table-column prop="loginIp" label="登录IP" min-width="240" show-overflow-tooltip></el-table-column>

            <el-table-column label="操作" align="center" width="210" fixed="right">
              <template #default="scope">
                <el-button-group>
                  <el-button text type="primary" icon="EditPen" @click="edit(scope.row)">编辑</el-button>
                  <el-button text type="danger" icon="Delete" @click="del(scope.row)">删除</el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <TablePagination
            v-model:paging="dataParams"
            :total="total"
            @update:page-size="handleSizeChange"
            @update:current-page="handleCurrentChange"
          ></TablePagination>
        </div>
      </pane>
    </splitpanes>

    <!-- 弹窗 -->
    <TableForm v-model="showForm" :form-init="formInit" :form-mode="formMode" @submit="submitForm"></TableForm>
  </div>
</template>

<script setup name="user">
import { onMounted, ref, watch } from 'vue'
import { userFindAll, register, userUpdate, userRemove, userRemoveBatch } from '@/api/system/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isTruthy } from '@/utils/judge'
import TablePagination from '@/components/TablePagination/TablePagination.vue'
import TableFilter from './components/TableFilter.vue'
import TableForm from './components/TableForm.vue'
import { useDict } from '@/hooks/useDict'
import DictTag from '@/components/DictTag/DictTag.vue'
// 分窗组件
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import { departmentFindAll } from '@/api/system/department'
import { buildTree } from '@/utils'

const { sys_status } = useDict('sys_status')

const loading = ref(true) // 加载中
const dataParams = ref({ pageNum: 1, pageSize: 20, sortField: 'createTime', sortOrder: 'DESC' }) // 筛选参数
const tableData = ref([]) // 表格数据
const total = ref(0) // 总数
const showFilter = ref(true) // 头部筛选栏显示
const showForm = ref(false) // 表单弹窗
const formInit = ref({}) // 表单初始值
const formMode = ref('') // 表单模式 add / edit
const batchSelection = ref([]) // 多选

onMounted(() => {
  handleTable(dataParams.value)
  queryDepartment()
})

// 筛选
function submitFilter(e) {
  Object.assign(dataParams.value, e)
  handleTable(dataParams.value)
}
function resetFilter() {
  delete dataParams.value.department
  refresh()
}

// 查
async function handleTable(params) {
  loading.value = true
  const res = await userFindAll(params)
  tableData.value = res.data || []
  total.value = res.total
  loading.value = false
}

// 增
function add() {
  formInit.value = {} // 置空参数
  formMode.value = 'add'
  showForm.value = true
}

// 改
function edit(row) {
  formInit.value = row // 携带参数
  formMode.value = 'edit'
  showForm.value = true
}

// 删
function del(row) {
  const { id, name } = row
  ElMessageBox.confirm(`确认删除『 ${name} 』吗？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 确认删除操作
    const deleteRes = await userRemove({ id })
    ElMessage({
      type: 'success',
      message: deleteRes?.msg
    })
    refresh()
  })
}

// 刷新
function refresh() {
  // 置空数据
  tableData.value = []
  batchSelection.value = []
  handleTable(dataParams.value)
}

// 多选
function selectionChange(e) {
  batchSelection.value = e.map((item) => item.id)
}

// 批量删除
function batchDelete() {
  if (!isTruthy(batchSelection.value, 'arr')) return
  ElMessageBox.confirm(`确认批量删除所选项吗？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 确认批量删除操作
    const deleteRes = await userRemoveBatch({
      ids: batchSelection.value
    })
    ElMessage({
      type: 'success',
      message: deleteRes?.msg
    })
    refresh()
  })
}

// 提交表单
async function submitForm(e) {
  try {
    let result = {}
    switch (e.mode) {
      case 'add':
        // 新增添加
        result = await register(e.data)
        break
      case 'edit':
        // 编辑更新
        result = await userUpdate(e.data)
        break
    }
    if (result.success) {
      showForm.value = false
      ElNotification({
        type: 'success',
        title: 'Success',
        message: result?.msg
      })
      refresh()
    }
  } catch (error) {
    console.warn(error.msg)
  }
}

// 分页
function handleSizeChange(e) {
  dataParams.value.pageSize = e
  handleTable(dataParams.value)
}
function handleCurrentChange(e) {
  dataParams.value.pageNum = e
  handleTable(dataParams.value)
}

/**
 * 部门相关
 */
const departmentLabel = ref('')
const departmentList = ref([])
const treeRef = ref()

async function queryDepartment() {
  const res = await departmentFindAll({ pageSize: -1, status: 1 })
  const tempData = res.data || []
  departmentList.value = buildTree(tempData)
}

// 部门过滤
watch(departmentLabel, (newVal) => {
  treeRef.value.filter(newVal)
})
function filterDepartment(val, data) {
  if (!val) return true
  return data.label.includes(val)
}

// 部门点击
function tapDepartment(e) {
  // 点击有效子节点
  if (e.parent) {
    dataParams.value.department = e.name
    handleTable(dataParams.value)
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  :deep(.splitpanes.default-theme) {
    .splitpanes__pane {
      background-color: unset;
    }
    .splitpanes__splitter {
      border-left: none;
      background-color: unset;
      width: 16px;

      &::before,
      &::after {
        background-color: #fff;
      }
    }
  }

  .department-container {
    width: 100%;
    height: 100%;
    padding: var(--page-padding);
  }
}
</style>
